from django.utils import timezone  # django转换UTC时间为本地时间
from kubernetes import client
from kubernetes.client.rest import ApiException


class OprationPodsApi():
    '''操作容器组'''

    def __init__(self, namespace):
        self.namespace = namespace
        from kubernetes import config
        config.load_kube_config(config_file="./kube_conf/local.conf")
        self.coreApi_v1 = client.CoreV1Api()
        self.extensions_v1beta1 = client.AppsV1Api()

    def get_pods_api(self):
        '''获取容器组'''

        pods_res = self.coreApi_v1.list_namespaced_pod(namespace=self.namespace, async_req=True).get()  # 容器组
        deployment_res = self.extensions_v1beta1.list_namespaced_deployment(namespace=self.namespace,
                                                                            async_req=True).get()
        results = []
        for pod_info in pods_res.items:
            pods_group = {}
            pods_group['name'] = pod_info.metadata.name
            for deployment in deployment_res.items:
                if deployment.metadata.labels is not None:
                    if deployment.metadata.labels.get('app') == pod_info.metadata.labels.get('app'):
                        pods_group['deployment_name'] = deployment.metadata.name
                else:
                    pods_group['deployment_name'] = deployment.metadata.labels
            if pod_info.status.phase == 'Pending':
                pods_group['restart_number'] = 'unknown'
                pods_group['status'] = pod_info.status.phase
                pods_group['message'] = 'unknown'
                pods_group['start_time'] = 'unknown'
                pods_group['node_ip'] = 'unknown'
                pods_group['pod_ip'] = 'unknown'
                pods_group['start_time'] = 'unknown'
            else:
                for container_status in pod_info.status.container_statuses:
                    pods_group['restart_number'] = container_status.restart_count
                    pods_group['status'] = pod_info.status.phase
                    if container_status.state.waiting is not None:
                        pods_group['message'] = container_status.state.waiting.message
                pods_group['node_ip'] = pod_info.status.host_ip
                pods_group['pod_ip'] = pod_info.status.pod_ip
                pods_group['start_time'] = timezone.localtime(pod_info.status.start_time).strftime("%Y-%m-%d %H:%M:%S")
                pods_group['create_time'] = timezone.localtime(pod_info.metadata.creation_timestamp).strftime(
                    "%Y-%m-%d %H:%M:%S")
            results.append(pods_group)

        return results


def search_pods_api(self, search):
    '''搜索查询单个pod信息'''

    results = []
    for pods in self.get_pods_api():
        if search == pods.get('deployment_name'):
            results.append(pods)
    return results


def restart_pods_api(self, pod_name):
    '''重启pod实例'''

    Body = client.V1DeleteOptions(
        propagation_policy='Foreground',
        grace_period_seconds=3
    )
    try:
        self.coreApi_v1.delete_namespaced_pod(namespace=self.namespace, name=pod_name, body=Body, async_req=True).get()
    except ApiException as e:
        return {'code': 500, 'msg': '%s 重启失败' % pod_name}
    else:
        return {'msg': 'pod %s 重启成功' % pod_name}
